package com.itheima.server.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.autoconfig.template.HuanXinTemplate;
import com.itheima.commons.utils.Constants;
import com.itheima.dubbo.api.*;
import com.itheima.model.domain.User;
import com.itheima.model.domain.UserInfo;
import com.itheima.model.mongo.Comment;
import com.itheima.model.mongo.Friend;
import com.itheima.model.vo.*;
import com.itheima.server.exception.BusinessException;
import com.itheima.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessageService {

    @DubboReference
    private UserApi userApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @DubboReference
    private FriendApi friendApi;
    @DubboReference
    private AnnouncementsApi announcementsApi;
    @DubboReference
    private CommentsApi commentsApi;



    //根据环信id查询用户信息
    public UserInfoVo findUserInfoByHuanxin(String huanxinId) {
        User user = userApi.findByHuanxinId(huanxinId);
        UserInfo userInfo = userInfoApi.findById(user.getId());

        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        if(userInfo.getAge()!=null){
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }
    //建立好友关系
    public void contacts(Long friendId) {
        //将好友关系注册到环信
        Boolean res = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(),
                Constants.HX_USER_PREFIX + friendId);
        if(!res){
            throw new BusinessException(ErrorResult.error());
        }

        //注册成功，记录好友关系到mongodb
        friendApi.save(UserHolder.getUserId(),friendId);
    }
    //查询好友列表
    public PageResult findFriends(Integer page, Integer pagesize, String keyword) {
        //查询用户列表
        List<Friend>  list=friendApi.findByUserId(UserHolder.getUserId(),page,pagesize);
        //根据用户的id查询用户详情
        List<Long> friendIds = CollUtil.getFieldValues(list, "friendId",Long.class);
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(keyword);
        PageResult userInfos = userInfoApi.findByIds(friendIds, userInfo, page, pagesize);
        //构造vo对象
        List<UserInfo> items = (List<UserInfo>) userInfos.getItems();
        List<ContactVo> vos = new ArrayList<>();
        for (UserInfo userInfo1 : items) {
            vos.add(ContactVo.init(userInfo1));
        }
        userInfos.setItems(vos);
        return userInfos;
    }
    /*删除好友关系*/
    public void unContacts(Long friendId) {
        //将好友关系从环信删除
        Boolean res = huanXinTemplate.deleteContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(), Constants.HX_USER_PREFIX + friendId);
        if(!res){
            throw new BusinessException(ErrorResult.error());
        }

        //注册成功，记录好友关系到mongodb
        friendApi.delete(UserHolder.getUserId(),friendId);
    }


    // 分页查询公告列表
    public PageResult getAnnouncements(Integer page, Integer pagesize) {
        // 调用Api查询公告列表
        IPage<AnnouncementVo> announcementIPage = announcementsApi.getAnnouncements(page,pagesize);

        // 将查询到的IPage对象的内容封装到PageResult中返回
        return new PageResult(page,pagesize,announcementIPage.getTotal(),announcementIPage.getRecords());
    }

    // 分页查询评论该用户的评论列表
    public PageResult getComments(Integer page, Integer pagesize) {
        // 调用Api查询评论列表
        List<Comment> commentList = commentsApi.getComments(UserHolder.getUserId(), page, pagesize);
        // 获取评论的用户id
        List<Long> userIds = CollUtil.getFieldValues(commentList, "userId", Long.class);
        if (CollUtil.isEmpty(userIds)){
            return new PageResult(page,pagesize, (long)0,null);
        }
        // 根据用户id获取用户详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        // 封装对象并返回
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : commentList) {
            UserInfo userInfo = map.get(comment.getUserId());
            CommentVo vo = CommentVo.init(userInfo, comment);
            vos.add(vo);
        }
        // 将查询到的vos对象的内容封装到PageResult中并返回
        return new PageResult(page,pagesize, (long) vos.size(),vos);
    }

    // 分页查询点赞该用户的点赞列表
    public PageResult getLikes(Integer page, Integer pagesize) {
        // 调用Api查询评论列表
        List<Comment> commentList = commentsApi.getLikes(UserHolder.getUserId(),page,pagesize);
        // 获取点赞的用户id
        List<Long> userIds = CollUtil.getFieldValues(commentList, "userId", Long.class);
        // 根据用户id获取用户详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        // 封装对象并返回
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : commentList) {
            UserInfo userInfo = map.get(comment.getUserId());
            CommentVo vo = CommentVo.init(userInfo, comment);
            vos.add(vo);
        }
        // 将查询到的vos对象的内容封装到PageResult中并返回
        return new PageResult(page,pagesize, (long) vos.size(),vos);
    }

    // 分页查询点赞该用户的喜欢列表
    public PageResult getLoves(Integer page, Integer pagesize) {
        // 调用Api查询评论列表
        List<Comment> commentList = commentsApi.getLoves(UserHolder.getUserId(),page,pagesize);
        // 获取点赞的用户id
        List<Long> userIds = CollUtil.getFieldValues(commentList, "userId", Long.class);
        // 根据用户id获取用户详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        // 封装对象并返回
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : commentList) {
            UserInfo userInfo = map.get(comment.getUserId());
            CommentVo vo = CommentVo.init(userInfo, comment);
            vos.add(vo);
        }
        // 将查询到的vos对象的内容封装到PageResult中并返回
        return new PageResult(page,pagesize, (long) vos.size(),vos);
    }

}
